<!DOCTYPE html>
<html>

<head>
  <title>Context Propagation in Quarkus</title>
  <script id="adobe_dtm" src="https://www.redhat.com/dtm.js" type="text/javascript"></script>
  <script src="/assets/javascript/highlight.pack.js" type="text/javascript"></script>
  <META HTTP-EQUIV='Content-Security-Policy' CONTENT="default-src 'none'; script-src 'self' 'unsafe-eval' 'sha256-ANpuoVzuSex6VhqpYgsG25OHWVA1I+F6aGU04LoI+5s=' 'sha256-ipy9P/3rZZW06mTLAR0EnXvxSNcnfSDPLDuh3kzbB1w=' js.bizographics.com https://www.redhat.com assets.adobedtm.com jsonip.com https://ajax.googleapis.com https://www.googletagmanager.com https://www.google-analytics.com https://use.fontawesome.com; style-src 'self' https://fonts.googleapis.com https://use.fontawesome.com; img-src 'self' *; media-src 'self' ; frame-src https://www.googletagmanager.com https://www.youtube.com; frame-ancestors 'none'; base-uri 'none'; object-src 'none'; form-action 'none'; font-src 'self' https://use.fontawesome.com https://fonts.gstatic.com;">
  <META HTTP-EQUIV='X-Frame-Options' CONTENT="DENY">
  <META HTTP-EQUIV='X-XSS-Protection' CONTENT="1; mode=block">
  <META HTTP-EQUIV='X-Content-Type-Options' CONTENT="nosniff">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Quarkus: Supersonic Subatomic Java">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:site" content="@QuarkusIO"> 
  <meta name="twitter:creator" content="@QuarkusIO">
  <meta property="og:url" content="https://quarkus.io/guides/context-propagation" />
  <meta property="og:title" content="Context Propagation in Quarkus" />
  <meta property="og:description" content="Quarkus: Supersonic Subatomic Java" />
  <meta property="og:image" content="/assets/images/quarkus_card.png" />
  <link rel="canonical" href="https://quarkus.io/guides/context-propagation">
  <link rel="shortcut icon" type="image/png" href="/favicon.ico" >
  <link rel="stylesheet" href="https://quarkus.io/guides/stylesheet/config.css" />
  <link rel="stylesheet" href="/assets/css/main.css" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
  <link rel="alternate" type="application/rss+xml"  href="https://quarkus.io/feed.xml" title="Quarkus">
  <script src="https://quarkus.io/assets/javascript/goan.js" type="text/javascript"></script>
  <script src="https://quarkus.io/assets/javascript/hl.js" type="text/javascript"></script>
</head>

<body class="guides">
  <!-- Google Tag Manager (noscript) -->
  <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-NJWS5L"
  height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
  <!-- End Google Tag Manager (noscript) -->

  <div class="nav-wrapper">
  <div class="grid-wrapper">
    <div class="width-12-12">
      <input type="checkbox" id="checkbox" />
      <nav id="main-nav" class="main-nav">
  <div class="container">
    <div class="logo-wrapper">
      
        <a href="/"><img src="/assets/images/quarkus_logo_horizontal_rgb_600px_reverse.png" class="project-logo" title="Quarkus"></a>
      
    </div>
    <label class="nav-toggle" for="checkbox">
      <i class="fa fa-bars"></i>
    </label>
    <div id="menu" class="menu">
      <span>
        <a href="/get-started/" class="">Get Started</a>
      </span>
      <span>
        <a href="/guides/" class="active">Guides</a>
      </span>
      <span>
        <a href="/community/" class="">Community</a>
      </span>
      <span>
        <a href="/support/" class="">Support</a>
      </span>
      <span>
        <a href="/blog/" class="">Blog</a>
      </span>
      <span>
        <a href="https://code.quarkus.io" class="button-cta secondary white">Start Coding</a>
      </span>
    </div>
  </div>
      </nav>
    </div>
  </div>
</div>

  <div class="content">
    <div class="guide">
  <div class="width-12-12">
    <h1 class="text-caps">Context Propagation in Quarkus</h1>
    <div class="hide-mobile toc"><ul class="sectlevel1">
<li><a href="#setting-it-up">Setting it up</a></li>
<li><a href="#usage-example-with-mutiny">Usage example with Mutiny</a></li>
<li><a href="#usage-example-for-completionstage">Usage example for <code>CompletionStage</code></a></li>
<li><a href="#adding-support-for-rxjava2">Adding support for RxJava2</a></li>
</ul></div>
    <div>
      <div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Traditional blocking code uses <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ThreadLocal.html"><code>ThreadLocal</code></a>
 variables to store contextual objects in order to avoid
passing them as parameters everywhere. Many Quarkus extensions require those contextual objects to operate
properly: <a href="rest-json">RESTEasy</a>, <a href="cdi-reference">ArC</a> and <a href="transaction">Transaction</a>
for example.</p>
</div>
<div class="paragraph">
<p>If you write reactive/async code, you have to cut your work into a pipeline of code blocks that get executed
"later", and in practice after the method you defined them in have returned. As such, <code>try/finally</code> blocks
as well as <code>ThreadLocal</code> variables stop working, because your reactive code gets executed in another thread,
after the caller ran its <code>finally</code> block.</p>
</div>
<div class="paragraph">
<p><a href="https://github.com/eclipse/microprofile-context-propagation">MicroProfile Context Propagation</a> was made to
make those Quarkus extensions work properly in reactive/async settings. It works by capturing those contextual
values that used to be in thread-locals, and restoring them when your code is called.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="setting-it-up"><a class="anchor" href="#setting-it-up"></a>Setting it up</h2>
<div class="sectionbody">
<div class="paragraph">
<p>If you are using <a href="http://smallrye.io/smallrye-mutiny">Mutiny</a> (the <code>quarkus-mutiny</code> extension), you just need to add the
the <code>quarkus-smallrye-context-propagation</code> extension to enable context propagation.</p>
</div>
<div class="paragraph">
<p>In other words, add the following dependencies to your <code>pom.xml</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="xml" class="language-xml hljs">&lt;dependencies&gt;
    &lt;!-- Mutiny and RestEasy support extensions if not already included --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
        &lt;artifactId&gt;quarkus-mutiny&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
        &lt;artifactId&gt;quarkus-resteasy-mutiny&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;!-- Context Propagation extension --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
        &lt;artifactId&gt;quarkus-smallrye-context-propagation&lt;/artifactId&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>With this, you will get context propagation for ArC, RESTEasy and transactions, if you are using them.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="usage-example-with-mutiny"><a class="anchor" href="#usage-example-with-mutiny"></a>Usage example with Mutiny</h2>
<div class="sectionbody">
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="fa icon-tip" title="Tip"></i>
</td>
<td class="content">
<div class="title">Mutiny</div>
<div class="paragraph">
<p>This section uses Mutiny reactive types, if you&#8217;re not familiar with them, read the <a href="getting-started-reactive#mutiny">Getting Started with Reactive guide</a> first.</p>
</div>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Let&#8217;s write a REST endpoint that reads the next 3 items from a <a href="kafka">Kafka topic</a>, stores them in a database using
<a href="hibernate-orm-panache">Hibernate ORM with Panache</a> (all in the same transaction) before returning
them to the client, you can do it like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">    // Get the prices stream
    @Inject
    @Channel("prices") Publisher&lt;Double&gt; prices;

    @Transactional
    @GET
    @Path("/prices")
    @Produces(MediaType.SERVER_SENT_EVENTS)
    @SseElementType(MediaType.TEXT_PLAIN)
    public Publisher&lt;Double&gt; prices() {
        // get the next three prices from the price stream
        return Multi.createFrom().publisher(prices)
                .transform().byTakingFirstItems(3)
                .map(price -&gt; {
                    // store each price before we send them
                    Price priceEntity = new Price();
                    priceEntity.value = price;
                    // here we are all in the same transaction
                    // thanks to context propagation
                    priceEntity.persist();
                    return price;
                    // the transaction is committed once the stream completes
                });
    }</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice that thanks to Mutiny support for context propagation, this works out of the box.
The 3 items are persisted using the same transaction and this transaction is committed when the stream completes.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="usage-example-for-completionstage"><a class="anchor" href="#usage-example-for-completionstage"></a>Usage example for <code>CompletionStage</code></h2>
<div class="sectionbody">
<div class="paragraph">
<p>If you are using <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/CompletionStage.html"><code>CompletionStage</code></a>
you need manual context propagation. You can do that by injecting a <code>ThreadContext</code>
or <code>ManagedExecutor</code> that will propagate every context. For example, here we use the <a href="vertx">Vert.x Web Client</a>
to get the list of Star Wars people, then store them in the database using
<a href="hibernate-orm-panache">Hibernate ORM with Panache</a> (all in the same transaction) before returning
them to the client as JSON using <a href="rest-json">JSON-B or Jackson</a>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="java" class="language-java hljs">    @Inject ThreadContext threadContext;
    @Inject ManagedExecutor managedExecutor;
    @Inject Vertx vertx;

    @Transactional
    @GET
    @Path("/people")
    @Produces(MediaType.APPLICATION_JSON)
    public CompletionStage&lt;List&lt;Person&gt;&gt; people() throws SystemException {
        // Create a REST client to the Star Wars API
        WebClient client = WebClient.create(vertx,
                         new WebClientOptions()
                          .setDefaultHost("swapi.co")
                          .setDefaultPort(443)
                          .setSsl(true));
        // get the list of Star Wars people, with context capture
        return threadContext.withContextCapture(client.get("/api/people/").send())
                .thenApplyAsync(response -&gt; {
                    JsonObject json = response.bodyAsJsonObject();
                    List&lt;Person&gt; persons = new ArrayList&lt;&gt;(json.getInteger("count"));
                    // Store them in the DB
                    // Note that we're still in the same transaction as the outer method
                    for (Object element : json.getJsonArray("results")) {
                        Person person = new Person();
                        person.name = ((JsonObject) element).getString("name");
                        person.persist();
                        persons.add(person);
                    }
                    return persons;
                }, managedExecutor);
    }</code></pre>
</div>
</div>
<div class="paragraph">
<p>Using <code>ThreadContext</code> or <code>ManagedExecutor</code> you can wrap most useful functional types and <code>CompletionStage</code>
in order to get context propagated.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The injected <code>ManagedExecutor</code> uses the Quarkus thread pool.</p>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="adding-support-for-rxjava2"><a class="anchor" href="#adding-support-for-rxjava2"></a>Adding support for RxJava2</h2>
<div class="sectionbody">
<div class="paragraph">
<p>You need to include the following modules to get RxJava2 support:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code data-lang="xml" class="language-xml hljs">&lt;dependencies&gt;
    &lt;!-- Automatic context propagation for RxJava2 --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;io.smallrye&lt;/groupId&gt;
        &lt;artifactId&gt;smallrye-context-propagation-propagators-rxjava2&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;!--
    Required if you want transactions extended to the end of methods returning
    an RxJava2 type.
     --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;io.smallrye.reactive&lt;/groupId&gt;
        &lt;artifactId&gt;smallrye-reactive-converter-rxjava2&lt;/artifactId&gt;
    &lt;/dependency&gt;
    &lt;!-- Required if you return RxJava2 types from your REST endpoints --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.jboss.resteasy&lt;/groupId&gt;
        &lt;artifactId&gt;resteasy-rxjava2&lt;/artifactId&gt;
    &lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>
</div>
</div>
</div>
</div>
    </div>
  </div>
</div>

  </div>

  <div class="content project-footer">
  <div class="footer-section">
    <div class="logo-wrapper">
      <a href="/"><img src="/assets/images/quarkus_logo_horizontal_rgb_reverse.svg" class="project-logo" title="Quarkus"></a>
    </div>
  </div>
  <div class="grid-wrapper">
    <p class="grid__item width-3-12">Quarkus is open. All dependencies of this project are available under the <a href='https://www.apache.org/licenses/LICENSE-2.0' target='_blank'>Apache Software License 2.0</a> or compatible license.<br /><br />This website was built with <a href='https://jekyllrb.com/' target='_blank'>Jekyll</a>, is hosted on <a href='https://pages.github.com/' target='_blank'>Github Pages</a> and is completely open source. If you want to make it better, <a href='https://github.com/quarkusio/quarkusio.github.io' target='_blank'>fork the website</a> and show us what you’ve got.</p>

    
      <div class="width-1-12 project-links">
        <span>Navigation</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="/">Home</a></li>
          
            <li><a href="/guides">Guides</a></li>
          
            <li><a href="/community/#contributing">Contribute</a></li>
          
            <li><a href="/faq">FAQ</a></li>
          
            <li><a href="/get-started">Get Started</a></li>
          
        </ul>
      </div>
    
      <div class="width-1-12 project-links">
        <span>Contribute</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="https://twitter.com/quarkusio">Follow us</a></li>
          
            <li><a href="https://github.com/quarkusio">GitHub</a></li>
          
            <li><a href="/security">Security&nbsp;policy</a></li>
          
        </ul>
      </div>
    
      <div class="width-1-12 project-links">
        <span>Get Help</span>
        <ul class="footer-links width-1-12">
          
            <li><a href="https://groups.google.com/forum/#!forum/quarkus-dev">Forums</a></li>
          
            <li><a href="https://quarkusio.zulipchat.com">Chatroom</a></li>
          
        </ul>
      </div>
    

    
      <div class="width-3-12 more-links">
        <span>Quarkus is made of community projects</span>
        <ul class="footer-links">
          
            <li><a href="https://vertx.io/" target="_blank">Eclipse Vert.x</a></li>
          
            <li><a href="https://microprofile.io" target="_blank">Eclipse MicroProfile</a></li>
          
            <li><a href="https://hibernate.org" target="_blank">Hibernate</a></li>
          
            <li><a href="https://netty.io" target="_blank">Netty</a></li>
          
            <li><a href="https://resteasy.github.io" target="_blank">RESTEasy</a></li>
          
            <li><a href="https://camel.apache.org" target="_blank">Apache Camel</a></li>
          
            <li><a href="https://code.quarkus.io/" target="_blank">And many more...</a></li>
          
        </ul>
      </div>
    
  </div>
</div>
  <div class="content redhat-footer">
  <div class="grid-wrapper">
    <span class="licence">
      <i class="fab fa-creative-commons"></i><i class="fab fa-creative-commons-by"></i> <a href="https://creativecommons.org/licenses/by/3.0/" target="_blank">CC by 3.0</a> | <a href="https://www.redhat.com/en/about/privacy-policy">Privacy Policy</a>
    </span>
    <span class="redhat">
      Sponsored by
    </span>
    <span class="redhat-logo">
      <a href="https://www.redhat.com/" target="_blank"><img src="/assets/images/redhat_reversed.svg"></a>
    </span>
  </div>
</div>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" integrity="sha384-8gBf6Y4YYq7Jx97PIqmTwLPin4hxIzQw5aDmUg/DDhul9fFpbbLcLh3nTIIDJKhx" crossorigin="anonymous"></script>
  <script type="text/javascript" src="/assets/javascript/mobile-nav.js"></script>
  <script type="text/javascript" src="/assets/javascript/scroll-down.js"></script>
  <script src="/assets/javascript/satellite.js" type="text/javascript"></script>
  <script src="https://quarkus.io/guides/javascript/config.js" type="text/javascript"></script>
  <script src="/assets/javascript/search-filter.js" type="text/javascript"></script>
  <script src="/assets/javascript/back-to-top.js" type="text/javascript"></script>
</body>

</html>
